<template>
	<view>
		<image class="samePar bodyBg posAbso ltzero" src="../../../static/images/login/loginBg.png"></image>
		<!-- 答题进度 -->
		<exam-progress :currPercent="currPercent" :currIndex="currIndex" :queLen="queLen"></exam-progress>
		<!-- 答题 -->
		<view class="quesWrap padd">
			<view class="innerQues"
				v-for="(item,index) in queList"
				:key="index"
				v-show="(index+1) == currIndex"
			>
				<que-list :showQueLayerFlag="showQueLayerFlag" :item="item" :index="index" :currIndex="currIndex" @changeOptIndex="changeOptIndex"></que-list>
			</view>
		</view>
		<view class="botWrap">
			<button class="comBtn prev" :disabled="prevDisFlag" @tap="goPrevQue">上一题</button>
			<button class="comBtn next" :disabled="nextDisFlag" @tap="goNextQue" v-if="!lastQueFlag">下一题</button>
			<button class="comBtn next" :disabled="isDisabledFlag" @tap="goSubmit" v-if="lastQueFlag">提交</button>
		</view>
		<common-alert :showAlertFlag="showAlertFlag">
			<block v-if="backOpt == 'backUp'">
				<view class="alertContent">当前测试未完成,是否继续返回?</view>
				<view class="tui-alert-btn" :hover-stay-time="150">
					<view class="cancelBtn" @tap.stop="cancel">取消</view>
					<view class="sureBtn" @tap="sureLogOut">确认</view> 
				</view>
			</block>
			<block v-else>
				<view class="alertContentSys">经系统检测,您未正常答题或答题速度过快,本次测评无效,请重新开始测评以便获得更准确的测评结果!</view>
				<view class="tui-alert-btn" :hover-stay-time="150">
					<view class="cancelBtn" @tap.stop="cancel">取消</view>
					<view class="sureBtn" @tap="sureLogOut">重新测评</view> 
				</view>
			</block>
		</common-alert>
	</view>
</template>

<script>
	import ExamProgress from './components/ExamProgress'
	import QueList from './components/QueList'
	import { addZzXlcsSubmit } from '@/api/index/index'
	export default {
		components:{
			ExamProgress, 
			QueList
		},
		data(){
			return{
				prevDisFlag:true,
				nextDisFlag:false,
				queLen:0,
				currIndex:1,
				currPercent:0,
				percentIndex:0,
				queIndex:0,
				lastQueFlag:false,
				isGetLastFlag:false,
				cpId:'',
				orderId:'',
				queList:[],
				gzUrl:'',
				initTimeStamp:0,
				isDisabledFlag:false,
				showAlertFlag:false,
				isDoneFlag:false,
				popupShow:false,
				radius:true,
				backOpt:'backUp',
				canAnsFlag:true,
				showQueLayerFlag:false,
				fromPage:'',//cpDetPage->测评详情进来 gyDetPage->干预详情进来&我的测评下干预测评进来
				gyLogId:0,//干预详情中用户试测进来
				scaleOwner:''
			}
		},
		onLoad(option){
			this.fromPage = option.fromPage;
			if(this.fromPage == 'cpDetPage'){
				this.orderId = option.orderId;
			}else if(this.fromPage == 'gyDetPage'){
				this.gyLogId = option.gyLogId;
			}
			this.queList = uni.getStorageSync('queList');
			this.queLen = this.queList.length;
			this.initTimeStamp = new Date().getTime();
			this.scaleOwner = option.scaleOwner;
			setTimeout(()=>{
				uni.setNavigationBarTitle({
					title:option.cpTit
				})
			},100)
			var msg = this.backOpt == 'backUp' ? '当前测试未完成,是否继续返回?' : '经系统检测,您未正常答题或答题速度过快,本次测评无效,请重新开始测评以便获得更准确的测评结果!'
			wx.enableAlertBeforeUnload({
				message:msg,
				success:(res)=>{
					//console.log(res)
				},
				fail:(err=>{
					//console.log(err)
				})
			});
		},
		methods:{
			sureLogOut(){
				this.showAlertFlag = false;
				setTimeout(()=>{
					uni.navigateBack({
						delta:1
					})
				},500)
			},
			cancel(){
				this.showAlertFlag = false;
				setTimeout(()=>{
					this.backOpt = 'backUp';
				},100)
			},
			//单选题/判断题选择答案
			changeOptIndex(index,currNum){
				if(index > 0 ){
					if(this.queList[index - 1].optIndex == -1){
						//console.log("有个没做=" + index + '==' + (index-1)) 
						this.util.showToast('请先解答第' + (index - 1) + '题');
						return;
					}
				}
				if(this.queList[index].optIndex == -1){
					var timestamp=new Date().getTime();
					this.queList[index].timeStamp = timestamp;
					this.percentIndex ++;
					this.currPercent = Number(  this.percentIndex/this.queLen )*100;
				}
				if(this.canAnsFlag){
					this.queList[index].optIndex = currNum;//添加active
					this.canAnsFlag = false;
					this.showQueLayerFlag = true;
					
					this.queList[index].labelVal = this.queList[index].optionList[currNum].value;
					if(this.scaleOwner == 'gz'){
						this.queList[index].currAns = this.queList[index].optionList[currNum].optionId;
					}else if(this.scaleOwner == 'hgz'){//2024-08-28新增
						this.queList[index].currAns = 1;
						this.queList[index].order = answerArray[this.queList[index].labelVal - 1];
					}
					
					if(this.percentIndex == this.queLen && this.currIndex == this.percentIndex){
						this.lastQueFlag = true;
						this.canAnsFlag = true;
					}
					if(this.lastQueFlag){
						setTimeout(()=>{
							this.showQueLayerFlag = false;
						},300);
						return;
					}
					setTimeout(()=>{
						this.currIndex ++;
						this.prevDisFlag = false;
						this.canAnsFlag = true;
						this.showQueLayerFlag = false;
						if(this.currIndex == this.percentIndex){
							this.lastQueFlag = true;
						}
					},300)
				}
			},
			goPrevQue(){
				this.currIndex --;
				this.lastQueFlag = false;
				if(this.currIndex == 1){
					this.prevDisFlag = true;
					return; 
				}
			},
			goNextQue(){
				if(this.queList[Number(this.currIndex-1)].optIndex == -1){
					this.util.showToast('请选择答案');
					return;
				} 
				this.currIndex ++; 
				if(this.currIndex == this.queLen){ 
					this.lastQueFlag = true;
					return;
				} 
				if(this.currIndex > 1){
					this.prevDisFlag = false;
				}
			},
			goSubmit(){
				var resFlag = true;
				if(this.queList[Number(this.currIndex-1)].currAns === ''){
					this.util.showToast('请选择答案');
					return;
				}
				for(let i in this.queList){
					if(this.queList[i].currAns == ''){
						resFlag = false;
					}
				}
				if(!resFlag){
					this.util.showToast('请补全所有未做题');
					return;
				}
				var lastTimeStap = this.queList[this.currIndex-1].timeStamp;
				var useTime = lastTimeStap - this.initTimeStamp;
				if(Number(useTime/1000) < this.queLen){ 
					//经系统检测,您未正常答题,本次测评无效,请重新开始测评以便获得正确的测评结果
					this.backOpt = 'sysVerify';
					this.showAlertFlag = true;
					return;
				}
				this.isDisabledFlag = true;
				
				var answersObj = null;
				if(this.scaleOwner == 'gz'){
					answersObj = this.queList.map(item=>{
						return{ option_id:item.currAns,question_id:item.questionId }
					})
				}else if(this.scaleOwner == 'hgz'){
					answersObj = this.queList.map(item=>{
						return { a:Number(item.labelVal) - 1,id:item.questionId,order:item.order }
					})
				}
				// var answersObj = this.queList.map(item=>{
				// 	return{ option_id:item.currAns,question_id:item.questionId }
				// })
				var labelOptionObj = this.queList.map(item=>{
					return{ labelValue:item.labelVal,timestamp:item.timeStamp }
				})
				var field = { startTimestamp:this.initTimeStamp,labelOption:JSON.stringify( labelOptionObj ),answers:JSON.stringify( answersObj ) }
				if(this.fromPage == 'cpDetPage'){
					var userCpInfo = uni.getStorageSync('userCpInfo');
					var tmpField = { groupId:userCpInfo.groupId,orderId:this.orderId,userName:userCpInfo.userName,userSex:userCpInfo.userSex,
									userAge:userCpInfo.userAge,userWork:userCpInfo.userWork}
					Object.assign(field,tmpField)
				}else if(this.fromPage == 'gyDetPage'){//干预详情试测
					var tmpField = { gyLogId:this.gyLogId }
					Object.assign(field,tmpField)
				}
				
				// Object.assign( field,tmpField );
				// console.log(answersObj)
				// console.log(labelOptionObj)
				//console.log(field)
				this.util.showToast('提交中...');
				uni.showLoading({
					title:'提交中...',
					mask:true
				})
				let url = this.fromPage == 'cpDetPage' ? '/xlcs/addZzXlcsSubmit' : '/xlcs/addRepeatXlcsSubmit'
				addZzXlcsSubmit(field,url).then(res=>{
					//console.log(res)
					this.util.showToastSuc('提交成功');
					if(this.fromPage == 'cpDetPage'){
						if(res.data.datas.reportTag == 1){//reportTag->1立即显示测评报告 2不显示
							var logId = res.data.datas.logId;
							setTimeout(()=>{
								uni.navigateTo({
									url:'../cpReport/cpReport?logId=' + logId + '&fromPage=' + this.fromPage
								})
							},1500);
						}else{//跳转至结果页
							uni.navigateTo({
								url:'../cpResult/cpResult?fromPage='+ this.fromPage +'&isSuccNum=1&failTxt='
							})
						}
					}else if(this.fromPage == 'gyDetPage'){//测试完成暂时禁止看报告
						uni.showToast({ title: '测评成功' });
						setTimeout(()=>{
							wx.disableAlertBeforeUnload();
							let pages = getCurrentPages();
							let prevPage = pages[pages.length - 2];
							prevPage.$vm.isRefreshFlag = true;
							uni.navigateBack({delta:1})
						},1500);
					}
				}).catch(err=>{
					this.isDisabledFlag = false;
					uni.navigateTo({
						url:'../cpResult/cpResult?fromPage='+ this.fromPage +'&isSuccNum=0&failTxt=' + err.data.message
					})
				});
			}
		}
	}
</script>

<style lang="scss">
	@import url("/static/css/common/alert.css");
	.alertContentSys{
		padding: 20rpx;
		font-size: 32rpx; 
		color: $pss-text-color3;
	}
	.quesWrap{
		min-height: 300rpx;
	}
	.botWrap{
		width: 100%;
		display: flex;
		justify-content: center;
		margin-top: 100rpx;
		padding-bottom: 100rpx;
		.comBtn{
			width: 180rpx;
			height: 76rpx;
			line-height: 76rpx;
			border-radius: 10rpx;
			font-size: 30rpx;
			&.prev{
				margin-right: -60rpx;
			}
			&[disabled]{
				background: #eee;
				color: #fff; 
			}
		}
	}
	.bodyBg{
		z-index: -1;
	}
	page{
		height: 100%;
		// background: $pss-bg-primary;
		margin-top: 120rpx;
		margin-bottom: 150rpx; 
		position: relative;
	}
</style>